﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.DosenView
{
    public partial class QuizFormPage : PhoneApplicationPage
    {
        private Quiz quiz;
        private bool firstLoaded;

        public QuizFormPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
            {
                firstLoaded = false;
            }
            else
            {
                firstLoaded = true;
            }
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (firstLoaded && PhoneApplicationService.Current.State.ContainsKey(Config.QUIZ))
            {
                quiz = (Quiz)PhoneApplicationService.Current.State[Config.QUIZ];
                if (quiz.Id != null)
                {
                    textBoxNama.Text = quiz.Nama;
                    datePickerStart.Value = quiz.Awal;
                    datePickerEnd.Value = quiz.Akhir;
                    textBoxJumlah.Text = quiz.Jumlah.ToString();
                    //timePickerWaktu.Text = quiz.Waktu.ToString();
                    timePickerStart.Value = quiz.Mulai;
                    timePickerEnd.Value = quiz.Selesai;
                    if (quiz.DetMatkul.Id != null)
                        textPerkuliahan.Text = "Quiz " + quiz.DetMatkul.Matkul.Nama;
                    if (quiz.DetMatkul.Creator == null)
                    {
                        textBlockMatkul.Visibility = Visibility.Collapsed;
                        matkulList.Visibility = Visibility.Collapsed;
                    }
                }
                else
                {
                    if (quiz.DetMatkul.Id == null)
                    {
                        textBlockMatkul.Visibility = Visibility.Visible;
                        matkulList.Visibility = Visibility.Visible;
                        textPerkuliahan.Text = "Quiz Baru";
                        LoadPerkuliahan();
                    }
                    else
                    {
                        textBlockMatkul.Visibility = Visibility.Collapsed;
                        matkulList.Visibility = Visibility.Collapsed;
                    }
                    textBoxNama.Text = "";
                    textBoxJumlah.Text = "";
                    if (quiz.DetMatkul.Id != null)
                        textPerkuliahan.Text = "Quiz " + quiz.DetMatkul.Matkul.Nama;
                }
            }
        }

        private void LoadPerkuliahan()
        {
            DetailMatkul kuliah = new DetailMatkul();
            kuliah.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
            string json = JsonConvert.SerializeObject(kuliah);

            string url = Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.PERKULIAHAN_DOSEN_VIEW_KEY;

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listPerkuliahan_UploadStringCompleted);
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void listPerkuliahan_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                DetailMatkulList list = JsonConvert.DeserializeObject<DetailMatkulList>(e.Result);
                matkulList.ItemsSource = list;
                if (quiz.DetMatkul.Matkul != null)
                    matkulList.SelectedItem = quiz.DetMatkul.Matkul;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void SaveQuiz(Quiz data)
        {
            string json = null, url = null;

            if (data.Id == null)
            {
                url = Config.Instance.QUIZ_SERVICE_URL() + Config.ADD_ACTION_KEY; //create
            }
            else
            {
                url = Config.Instance.QUIZ_SERVICE_URL() + Config.UPDATE_ACTION_KEY; //update
            }
            json = JsonConvert.SerializeObject(data);


            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(saveChange_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void saveChange_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                MessageBox.Show("Message : " + e.Result);

                if (e.Result.Contains("Success"))
                    NavigationService.GoBack();

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            if (matkulList.Visibility == Visibility.Visible)
                quiz.DetMatkul = (DetailMatkul)matkulList.SelectedItem;
            quiz.Nama = textBoxNama.Text;
            if (!Utility.isNumber(textBoxJumlah.Text))
                MessageBox.Show("Input harus angka dan tidak boleh 0");
            else
            {
                quiz.Awal = datePickerStart.Value.Value;
                datePickerEnd.Value = datePickerEnd.Value.Value < datePickerStart.Value.Value ? datePickerStart.Value.Value : datePickerEnd.Value.Value;
                quiz.Akhir = datePickerEnd.Value.Value;
                DateTime? tMulai = timePickerStart.Value;
                DateTime? tSelesai = timePickerEnd.Value;
                string sMulai = quiz.Awal.ToString("MM/dd/yyyy") + " " + tMulai.Value.ToString("HH:mm");
                quiz.Mulai = DateTime.Parse(sMulai);
                string sSelesai = quiz.Akhir.ToString("MM/dd/yyyy") + " " + tSelesai.Value.ToString("HH:mm");
                quiz.Selesai = DateTime.Parse(sSelesai);
                if (quiz.Selesai.Value < quiz.Mulai.Value)
                {
                    MessageBox.Show("Jam selesai harus lebih besar dari jam mulai");
                    return;
                }
                TimeSpan waktu = quiz.Selesai.Value.Subtract(quiz.Mulai.Value);
                quiz.Waktu = (int)waktu.TotalMinutes;
                quiz.Jumlah = int.Parse(textBoxJumlah.Text);
                SaveQuiz(quiz);
            }
        }

        private void buttonCancel_Click(object sender, System.EventArgs e)
        {
            NavigationService.GoBack();
        }

    }
}